﻿// 
//    Copyright 2010 The JaernCloud Project
// 
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
// 
//        http://www.apache.org/licenses/LICENSE-2.0
// 
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JaernCloud.Language.Compiler.Types;
using System.IO;
using JaernCloud.Language.Compiler.Types.Builtin.View;
using System.Web.UI;
using System.Dynamic;

namespace JaernCloud.Language.Runtime.View {
    
    /// <summary>
    /// Render capable node object (such as HTML elements)
    /// </summary>
    public class RenderNodeObject : NodeObject<IRenderNodeType>, IRenderNodeObject {

        public override INodeObject<IRenderNodeType> FromType(INodeType type, INodeObjectGenerator objectGenerator) {
            return new RenderNodeObject { _type = (IRenderNodeType)type, _objectGenerator = objectGenerator };
        }

        public string RenderId {
            get {
                var tag = Type.SourceNode.Tag;
                if (tag != null && !String.IsNullOrEmpty(tag.Id)) {
                    // the rendered node has an id - use that
                    return tag.ToString();
                }
                // build a selector to target the node
                var path = NodeTypeHelper.PathTo(Type, typeof(IViewNodeType));
                StringBuilder sb = new StringBuilder();
                foreach (var type in path) {
                    tag = type.SourceNode.Tag;
                    if (tag != null) {
                        sb.Append(tag);
                    }
                    sb.Append(' ');
                }
                if (sb.Length > 0) sb.Length--; //trim
                return sb.ToString();
            }
        }

        public override bool TryConvert(ConvertBinder binder, out object result) {
            foreach(object value in Values) {
                if (binder.ReturnType.IsAssignableFrom(value.GetType())) {
                    // TODO: Multiple values should be traversed in reverse (latest get's first dibs)
                    result = value;
                    return true;
                }
            }
            return base.TryConvert(binder, out result);
        }

        public void Render(INodeObject<INodeType> root, TextWriter writer) {
            // TODO: Move the HTML rendering to JaernCloud.Web?
            if (root.Type is IViewNodeType) {
                // we're starting to render the view
                if (this.Type is HTMLNodeType) {
                    HtmlTextWriter htmlWriter = new HtmlTextWriter(writer);
                    htmlWriter.WriteFullBeginTag("html");
                    IOrderedEnumerable<INodeObject<INodeType>> children = root.Children.OrderBy<INodeObject<INodeType>, int>((node) => { return node.Type.Name == "head" ? -1 : 0; });
                    foreach (var child in children) {
                        if (child is IRenderNodeObject) {
                            (child as IRenderNodeObject).Render(this, htmlWriter);
                        }
                    }
                    htmlWriter.WriteEndTag("html");
                    htmlWriter.Flush();
                    return;
                }
                throw new NotSupportedException(this.Type + " is not a supported view render type");
            }
            if (writer is HtmlTextWriter) {
                HtmlTextWriter htmlWriter = writer as HtmlTextWriter;
                htmlWriter.WriteBeginTag(Name);
                // TODO Write Id and Classes
                if (Type is AnchorNodeType) {
                    foreach (var child in Children) {
                        if (child.Type is IActionNodeType) {
                            IActionNodeType action = child.Type as IActionNodeType;
                            IActionNodeType target = action.Target;
                            IActionNodeTypeOwner owner = target.FindParent<IActionNodeTypeOwner>();
                            if(owner == null) {
                                throw new ActionException(target.SourceNode, "Action has no owner");
                            }
                            if(owner.SourceNode.Tag == null) {
                                throw new ActionException(owner.SourceNode, "Action owner has no tag to identify it");
                            }
                            StringBuilder actionText = new StringBuilder();
                            if (action.IsAjax) {
                                actionText.Append("return ($.jcl.ajax('");
                                actionText.Append(owner.SourceNode.Tag.ToString());
                                actionText.Append(" -> ").Append(action.ActionName);
                                actionText.Append("'));");
                                htmlWriter.WriteAttribute("href", "#");
                                htmlWriter.WriteAttribute("onclick", actionText.ToString());
                            } else {
                                throw new NotSupportedException("Only ajax actions are currently supported");
                            }
                        }
                    }
                }
                htmlWriter.Write(HtmlTextWriter.TagRightChar);
                if (Parent != null && Parent.Type is HTMLNodeType && this.Name == "head") {
                    // insert js dependencies (TODO: This should be handled in a more general way somehow)                    
                    htmlWriter.WriteBeginTag("script");
                    htmlWriter.WriteAttribute("src", "/Scripts/jquery-1.4.1.js");
                    htmlWriter.Write(HtmlTextWriter.TagRightChar);
                    htmlWriter.WriteEndTag("script");
                    htmlWriter.WriteBeginTag("script");
                    htmlWriter.WriteAttribute("src", "/Scripts/jaerncloud-0.1.js");
                    htmlWriter.Write(HtmlTextWriter.TagRightChar);
                    htmlWriter.WriteEndTag("script");
                }
                foreach (var child in Children) {
                    if (child is IRenderNodeObject) {
                        (child as IRenderNodeObject).Render(this, htmlWriter);
                    }
                    if (child is IExpressionNodeObject) {
                        dynamic value = (child as IExpressionNodeObject).ExpressionValue;
                        if (value != null) {
                            htmlWriter.Write((string)value);
                        }
                    }
                    if (child.Type is IConstantNodeType) {
                        htmlWriter.Write((child.Type as IConstantNodeType).Value);
                    }
                }
                htmlWriter.WriteEndTag(Name);
            }
        }

        public override string ToString() {
            return Type.SourceNode.Tag.ToString();
        }

    }
}
